<template>
  <el-dialog title="收货地址" :visible.sync="isOpen" ref="ruleForm">
    <el-form :model="form" ref="ruleForm" :rules="rules">
      <el-form-item label="角色名字" :label-width="'120px'" prop="name">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" :label-width="'120px'" prop="msg">
        <el-input v-model="form.msg" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit('ruleForm')">提交</el-button>
        <el-button @click="reset('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts">

import { Component, Vue } from 'vue-property-decorator'
import { addRole } from '@/api/permission'

@Component
export default class AddRole extends Vue {
  public isOpen = false

  public form = {
    name: '',
    msg: ''
  }

  submit (val:string) {
    (this.$refs[val] as any).validate(async (valid:string) => {
      if (valid) {
        const { data, meta: { msg, status } } = await addRole({ roleName: this.form.name, roleDesc: this.form.msg })
        this.$emit('render1', status, msg)
      } else {
        this.open('角色名或者描述格式错误', 'error')
        return false
      }
    })
  }

  reset (val:string) {
    this.form.name = ''
    this.form.msg = ''
  }

  nameReg (rule:any, value:any, callback:any) {
    if (/^[a-zA-Z]\w{2,5}$/.test(value)) return callback()
    return callback(new Error('角色名为字母开头3-6位的字母数字下划线组成'))
  }

  msgReg (rule:any, value:any, callback:any) {
    if (/^\w{3,20}$/.test(value)) return callback()
    return callback(new Error('描述为3-20位的字母数字下划线'))
  }

  public rules = {
    name: [{ validator: this.nameReg, trigger: 'blur' }],
    msg: [{ validator: this.msgReg, trigger: 'change' }]
  }

  // 提示框
  open (
    smg = '登陆成功',
    type: 'success' | 'warning' | 'info' | 'error' = 'success'
  ) {
    this.$message({
      message: smg,
      type: type
    })
  }
}
</script>

<style lang="less" scoped>

</style>
